package com.powernode.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.powernode.domain.Sku;
import com.powernode.feign.CartSkuFeign;
import com.powernode.model.CartItem;
import com.powernode.model.CartVo;
import com.powernode.model.ShopCart;
import com.powernode.vo.CartMoneyVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.powernode.mapper.BasketMapper;
import com.powernode.domain.Basket;
import com.powernode.service.BasketService;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

/**
*内容: 
*作者: cy
*/   
    
   
@Service
public class BasketServiceImpl extends ServiceImpl<BasketMapper, Basket> implements BasketService{
    @Autowired
    private BasketMapper basketMapper;

    @Autowired
    private CartSkuFeign cartSkuFeign;

    /**
     * 查询购物车中商品的数量
     *
     * @param openId
     * @return
     */
    @Override
    public Integer getBasketCount(String openId) {

        List<Object> objectList = basketMapper.selectObjs(new QueryWrapper<Basket>()
                .select("IFNULL(sum(basket_count),0)")
                .eq("user_id", openId)
        );
//  Integer count = basketMapper.selectUserCount(openId);
        return Integer.parseInt(objectList.get(0).toString());
    }

    /**
     * 修改购物车中商品的数量(添加/修改)
     *
     * @param openId
     * @param basket
     */
    @Override
    public void changeItem(String openId, Basket basket) {
        // 先查询购物车中 有没有 这一条记录
        Basket oldBasket = basketMapper.selectOne(new LambdaQueryWrapper<Basket>()
                .eq(Basket::getUserId, openId)
                .eq(Basket::getSkuId, basket.getSkuId())
        );
        if (ObjectUtils.isEmpty(oldBasket)) {
            // 就要新增
            basket.setUserId(openId);
            basket.setBasketDate(new Date());
            basketMapper.insert(basket);
            return;
        }
        // 不然就是修改
        int finalCount = oldBasket.getBasketCount() + basket.getBasketCount();
        if (finalCount < 0) {
            throw new IllegalArgumentException("购物车中的商品数量不能小于0");
        }
        if (finalCount == 0) {
            // 删掉
            basketMapper.deleteById(oldBasket.getBasketId());
            return;
        }
        oldBasket.setBasketCount(finalCount);
        oldBasket.setBasketDate(new Date());
        basketMapper.updateById(oldBasket);
    }

    /**
     * 查询购物车中商品的信息
     * 1.查询购物车表 拿到List<Basket>
     * 2.拿到skuIds
     * 3.远程调用商品模块 拿到List<sku>
     * 4.处理数据
     *
     * @param openId
     * @return
     */
    @Override
    public CartVo getCartInfo(String openId) {
        CartVo cartVo = new CartVo();
        List<Basket> basketList = basketMapper.selectList(new LambdaQueryWrapper<Basket>()
                .eq(Basket::getUserId, openId)
                .orderByDesc(Basket::getBasketDate)
        );
        if (CollectionUtils.isEmpty(basketList)) {
            return cartVo;
        }
        // 拿到skuIds
        List<Long> skuIds = basketList.stream()
                .map(Basket::getSkuId)
                .collect(Collectors.toList());
        // 远程调用商品模块 拿到List<sku>
        List<Sku> skuList = cartSkuFeign.getSkuListByIds(skuIds);
        if (CollectionUtils.isEmpty(skuList)) {
            throw new RuntimeException("服务器维护中");
        }
        // 核心目的 就是要组装 CartVo
        // 他有几个店铺 就要创建几个集合
        // 按照店铺id 来分组  key shopId  value 这个店铺对应的商品集合
        Map<Long, List<Basket>> shopMap = basketList.stream()
                .collect(Collectors.groupingBy(Basket::getShopId));

//        HashMap<Long, List<Basket>> myShopMap = new HashMap<>();
//        basketList.forEach(basket -> {
//            List<Basket> baskets = myShopMap.get(basket.getShopId());
//            if (CollectionUtils.isEmpty(baskets)) {
//                baskets = new ArrayList<>();
//                myShopMap.put(basket.getShopId(), baskets);
//            }
//            baskets.add(basket);
//        });
        ArrayList<ShopCart> shopCarts = new ArrayList<>();
        // 循环map
        shopMap.forEach((shopId, baskets) -> {
            // 循环一次 new 一个店铺对象
            ShopCart shopCart = new ShopCart();
            shopCarts.add(shopCart);
            ArrayList<CartItem> cartItems = new ArrayList<>();
            shopCart.setShopCartItems(cartItems);
            // 循环baskets
            baskets.forEach(basket -> {
                CartItem cartItem = new CartItem();
                BeanUtil.copyProperties(basket, cartItem, true);
                // 过滤出符合sku
                Sku sku1 = skuList.stream().filter(sku -> sku.getSkuId().equals(basket.getSkuId()))
                        .collect(Collectors.toList())
                        .get(0);
                BeanUtil.copyProperties(sku1, cartItem, true);
                cartItem.setChecked(true);
                cartItems.add(cartItem);
            });
        });
        cartVo.setShopCarts(shopCarts);
        return cartVo;
    }

    /**
     * 计算购物车中选中商品的总价
     * += 单价*数量
     *
     * @param basketIds
     * @return
     */
    @Override
    public CartMoneyVo calculateTotalPay(List<Long> basketIds) {
        CartMoneyVo cartMoneyVo = new CartMoneyVo();
        if (CollectionUtils.isEmpty(basketIds)) {
            return cartMoneyVo;
        }
        // 查询购物车集合
        List<Basket> basketList = basketMapper.selectBatchIds(basketIds);
        // 算价格 需要sku信息
        List<Long> skuIds = basketList.stream()
                .map(Basket::getSkuId)
                .collect(Collectors.toList());
        // 远程调用
        List<Sku> skuList = cartSkuFeign.getSkuListByIds(skuIds);
        if (CollectionUtils.isEmpty(skuList)) {
            throw new RuntimeException("服务器维护中");
        }
        List<BigDecimal> oneTotalMoneyList = new ArrayList<>();
        // 不能在 stream流做这种计算操作
        basketList.forEach(basket -> {
            Sku sku1 = skuList.stream().filter(sku -> sku.getSkuId().equals(basket.getSkuId()))
                    .collect(Collectors.toList())
                    .get(0);
            BigDecimal oneTotalMoney = sku1.getPrice().multiply(new BigDecimal(basket.getBasketCount()));
            oneTotalMoneyList.add(oneTotalMoney);
        });
        // 这样就是总金额
        BigDecimal totalMoney = oneTotalMoneyList.stream().reduce(BigDecimal::add).get();
        cartMoneyVo.setTotalMoney(totalMoney);
        cartMoneyVo.setFinalMoney(totalMoney);
        // 运费  满99 包邮 不满 的运费 6块
        if (totalMoney.compareTo(new BigDecimal(99)) < 0) {
            // 需要运费
            cartMoneyVo.setTransMoney(new BigDecimal(6));
            cartMoneyVo.setFinalMoney(totalMoney.add(new BigDecimal(6)));
        }
        return cartMoneyVo;
    }
}
